<template>
  <el-drawer
    v-model="visible"
    title="订单详情"
    size="600px"
    @close="handleClose"
  >
    <div v-if="order" class="order-detail-content">
      <el-card class="order-info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>订单信息</span>
          </div>
        </template>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单编号">{{ order.orderNumber }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ order.customerName }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ formatCurrency(order.orderAmount) }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">{{ getStatusText(order.orderStatus) }}</el-descriptions-item>
          <el-descriptions-item label="发票状态">{{ getInvoiceStatusText(order.invoiceStatus) }}</el-descriptions-item>
          <el-descriptions-item label="负责销售">{{ order.responsibleSalesman || '未分配' }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ order.customerName }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ order.contactPerson }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="order-actions" style="margin-top: 20px;">
          <el-button 
            v-if="order.orderStatus !== 'completed' && order.orderStatus !== 'cancelled'" 
            type="success" 
            @click="markAsCompleted"
            style="margin-right: 10px;"
          >
            标记为完成
          </el-button>
          <el-button 
            v-if="order.invoiceStatus === 'uninvoiced' && order.orderStatus === 'completed'" 
            type="warning" 
            @click="openInvoiceDialog"
            style="margin-right: 10px;"
          >
            开具发票
          </el-button>
        </div>
      </el-card>
      
      <el-card class="order-items-card" shadow="never" style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>订单明细</span>
          </div>
        </template>
        
        <el-table :data="order.orderItems" style="width: 100%">
          <el-table-column prop="productName" label="商品名称" min-width="150" />
          <el-table-column prop="sku" label="SKU" width="120" />
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="{ row }">
              ¥{{ formatCurrency(row.unitPrice) }}
            </template>
          </el-table-column>
          <el-table-column prop="subtotal" label="小计" width="100">
            <template #default="{ row }">
              ¥{{ formatCurrency(row.subtotal) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="120" />
        </el-table>
      </el-card>
    </div>
    
    <div v-else class="loading-container">
      <el-skeleton animated>
        <template #template>
          <el-skeleton-item variant="h3" style="width: 50%" />
          <div style="margin-top: 20px">
            <el-skeleton-item variant="p" style="width: 100%" />
            <el-skeleton-item variant="p" style="width: 100%; margin-top: 10px" />
            <el-skeleton-item variant="p" style="width: 100%; margin-top: 10px" />
          </div>
        </template>
      </el-skeleton>
    </div>
    
    <InvoiceDialog
      v-model="showInvoiceDialog"
      :order-data="order"
      @success="handleInvoiceSuccess"
    />
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch } from '@vue/runtime-core'
import { ElMessage } from 'element-plus'
import { getSalesOrderDetail } from '@/api/sales'
import type { Order } from '../types'
import InvoiceDialog from './InvoiceDialog.vue'

// 定义组件属性
interface Props {
  modelValue: boolean
  orderId?: number
}

const props = defineProps<Props>()

// 定义组件事件
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'refresh'): void
}>()

// 响应式数据
const visible = ref(false)
const order = ref<Order | null>(null)
const showInvoiceDialog = ref(false)

// 监听modelValue变化
watch(() => props.modelValue, (newVal: boolean) => {
  visible.value = newVal
  if (newVal && props.orderId) {
    loadOrderDetail(props.orderId)
  }
})

// 监听visible变化
watch(visible, (newVal: boolean) => {
  emit('update:modelValue', newVal)
  if (!newVal) {
    order.value = null
  }
})

// 获取订单详情
const loadOrderDetail = async (orderId: number) => {
  try {
    const response = await getSalesOrderDetail(orderId)
    order.value = response.data
  } catch (error) {
    ElMessage.error('获取订单详情失败')
    visible.value = false
  }
}

// 关闭抽屉
const handleClose = () => {
  visible.value = false
}

// 标记为完成
const markAsCompleted = async () => {
  try {
    // 这里应该调用API来更新订单状态
    // await updateOrderStatus(order.value!.id, 'completed')
    ElMessage.success('订单已标记为完成')
    emit('refresh')
    visible.value = false
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 打开发票对话框
const openInvoiceDialog = () => {
  showInvoiceDialog.value = true
}

// 处理发票成功
const handleInvoiceSuccess = () => {
  showInvoiceDialog.value = false
  ElMessage.success('发票开具成功')
  // 重新加载订单详情以更新发票状态
  if (props.orderId) {
    loadOrderDetail(props.orderId)
  }
  emit('refresh')
}

// 工具函数
const formatCurrency = (amount: number) => {
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待处理',
    confirmed: '已确认',
    processing: '处理中',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const getInvoiceStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    uninvoiced: '未开票',
    invoiced: '已开票',
    sent: '已发送'
  }
  return statusMap[status] || status
}
</script>

<style scoped lang="scss">
.order-detail-content {
  padding: 20px;
  
  .order-info-card,
  .order-items-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}

.loading-container {
  padding: 20px;
}
</style>